﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcContrib.Unity;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Lekker.Web.Mvc {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication, IUnityContainerAccessor {

        private static UnityContainer _container;

        public static IUnityContainer Container {
            get { return _container; }
        }

        IUnityContainer IUnityContainerAccessor.Container {
            get { return Container; }
        }

        protected void Application_Start() {

            InitializeContainer();
            RegisterRoutes(RouteTable.Routes);
        }

        /// <summary>
        /// Instantiate the container and add all Controllers that derive from 
        /// UnityController to the container.  Also associate the Controller 
        /// with the UnityContainer ControllerFactory.
        /// </summary>
        protected virtual void InitializeContainer() {
            if (_container == null) {
                _container = new UnityContainer();

                // Set the Unity Controller Factory
                ControllerBuilder.Current.SetControllerFactory(typeof(MvcContrib.Unity.UnityControllerFactory));

                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                section.Containers["lekkerContainer"].Configure(_container);
            }
        }

        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home",action = "Index",id = "" },   // Parameter defaults
                new[] { "Lekker.Web.Mvc.Controllers" }                  // Namespaces

            );

        }

    }
}